
// 进程池——基于匿名管道

#include <iostream>
#include <vector>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
class Channel
{
public:
    Channel(int wfd, pid_t subid)
        : _wfd(wfd), _subid(subid)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(_subid);
    }
    ~Channel() {}

    int getwfd() { return _wfd; }
    pid_t getsubid() { return _subid; }
    std::string getname() { return _name; }
    void Close()
    {
        close(_wfd);
    }
    void Wait()
    {
        pid_t id=waitpid(_subid,nullptr,0);
        (void)id;
    }

private:
    int _wfd;
    pid_t _subid; // 子进程id
    std::string _name;
};

class ChannelManager
{
public:
    ChannelManager() {}
    ~ChannelManager() {}
    void insert(int wfd, int subid)
    {
        _channels.emplace_back(wfd, subid);
    }
    void stopSubProcess()
    {
        for(auto& ch:_channels)
        {
            ch.Close();
        }
    }
    void waitSubProcess()
    {
        for(auto& ch:_channels)
        {
            ch.Wait();
        }
    }

private:
    std::vector<Channel> _channels;
};

const int defaultNum = 5;
class ProcessPool
{
public:
    ProcessPool(int process_num = defaultNum)
        : _process_num(process_num)
    {
    }
    // 开始形成进程池
    void initProcessPool()
    {
        for (int i = 0; i < _process_num; i++)
        {
            // 1,先创建匿名管道
            int pipefd[2] = {0};
            int n = pipe(pipefd); // 0读，1写
            if (n < 0)
            {
                std::cerr << "create pipe err\n";
                continue;
            }
            // 2，创建进程
            pid_t subid = fork();
            if (subid == 0)
            {
                // 子进程——关闭写端
                close(pipefd[1]);

                work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                // 父进程——关闭读端
                close(pipefd[0]);
                // 将写端加入管理中
                _channels.insert(pipefd[1], subid);
            }
        }
    }
    //关闭进程池
    void stop()
    {
        _channels.stopSubProcess();
        _channels.waitSubProcess();
    }
private:
    void work(int rfd)
    {
        while (true)
        {
            char buff[1024];
            int n=read(rfd,buff,sizeof(buff)-1);
            std::cout<<buff<<std::endl;
            if(n==0)
            {
                //写端关闭导致
                break;
            }
        }
    }

private:
    int _process_num;
    ChannelManager _channels;
};